<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 10px" v-if="this.$route.query.id!=null">
      <div style="display: inline-block;margin-left: 50px"><p>单据号：{{this.form.code}}</p></div>
      <div style="display: inline-block;margin-left: 200px"><p>状态：{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</p></div>
      <br>
      <div style="display: inline-block;margin-left: 50px"><p>操作人：{{ this.form.createBy }}</p></div>
      <div style="display: inline-block;margin-left: 200px"><p>操作时间：{{ this.form.createTime }}</p></div>
    </div>
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;">业务单据</h3>
      <el-row :gutter="10" class="mb8" style="margin: 10px 0">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="medium"
            @click="selectOrder"
            v-hasPermi="['system:product:add']"
          >新增</el-button>
        </el-col>
      </el-row>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table height="400px" v-loading="loading" :data="this.tblLogisticsSheetDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="业务单据号" align="left" prop="tblSaleOutSheet.code" width="300px"/>
          <el-table-column label="业务类型" align="left" prop="bizType" width="200">
            <template slot-scope="scope">
              <span>{{ '销售出库单'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" align="left" prop="tblSaleOutSheet.scName" width="150px"/>
          <el-table-column label="收件人" align="left" prop="tblSaleOutSheet.customerName" width="150px"/>
          <el-table-column label="操作时间" align="left" prop="tblSaleOutSheet.createTime" width="200px">
            <template slot-scope="scope">
              <span>{{parseTime(scope.row.tblSaleOutSheet.createTime, '{y}-{m}-{d}')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作人" align="left" prop="tblSaleOutSheet.createBy" width="150px"/>
        </el-table>
      </div>
    </div>


    <el-form :model="form" ref="" size="small" :inline="true" label-width="80px">
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">寄件人信息</h3>
        <el-form-item label="姓名" prop="senderName" style="margin:0 50px 0 20px">
          <el-input
            v-model="form.senderName"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="senderTelephone" style="margin:0 50px">
          <el-input
            v-model="form.senderTelephone"
            clearable
          />
        </el-form-item>
        <el-form-item label="地区" prop="senderValue" style="margin-left: 50px">
          <el-cascader
            v-model="form.senderValue"
            :options="options1"
            :props="{
                value:'id',
                label:'name',
                children:'children',expandTrigger: 'hover',
              }"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="senderAddress" style="margin-left: 20px">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.senderAddress"
            style="width: 1000px;"
          />
        </el-form-item>
      </div>

      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">收件人信息</h3>
        <el-form-item label="姓名" prop="receiverName" style="margin:0 50px 0 20px">
          <el-input
            v-model="form.receiverName"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="receiverTelephone" style="margin:0 50px">
          <el-input
            v-model="form.receiverTelephone"
            clearable
          />
        </el-form-item>
        <el-form-item label="地区" prop="receiverValue" style="margin-left: 50px">
          <el-cascader
            v-model="form.receiverValue"
            :options="options1"
            :props="{
                value:'id',
                label:'name',
                children:'children',expandTrigger: 'hover',
              }"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="receiverAddress" style="margin-left: 20px">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.receiverAddress"
            style="width: 1000px;"
          />
        </el-form-item>
      </div>

      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">物流单信息</h3>
        <el-form-item label="物流公司" prop="code" style="margin:0 50px 0 20px">
          <el-select v-model="form.logisticsCompanyId" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in logisticsCompany" :key="index" :label="item.name"
                       :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNo" style="margin:0 50px">
          <el-input
            v-model="form.logisticsNo"
            clearable
          />
        </el-form-item>
        <el-form-item label="总重量(kg)" prop="totalWeight" style="margin-left: 50px">
          <el-input
            v-model="form.totalWeight"
            clearable
          />
        </el-form-item>
        <el-form-item label="总体积(kg)" prop="code" style="margin:0 50px 0 20px">
          <el-input
            v-model="form.totalVolume"
            clearable
          />
        </el-form-item>
        <el-form-item label="物流费(元)" prop="totalAmount" style="margin-left: 50px">
          <el-input
            v-model="form.totalAmount"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注" prop="description" style="margin-left: 20px">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.description"
            style="width: 1000px;"
          />
        </el-form-item>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>


    <!-- 销售出库弹窗 -->
    <el-dialog title="选择" :visible.sync="saleOutFormVisible" width="1000px">
      <el-form :model="saleOutQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <div style="border: 1px gainsboro solid;border-radius: 3px;padding: 5px;align-items: center;display: flex;height: 70px">
          <el-form-item label="单号" prop="code" style="margin-top: 10px">
            <el-input
              v-model="saleOutQueryParams.code"
              placeholder="请输入单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="操作人" prop="createBy" style="margin-top: 10px">
            <el-select v-model="saleOutQueryParams.createBy" @keyup.enter.native="handleQuery" clearable>
              <el-option v-for="user in UserList" :key="user.id" :value="user.userId" :label="user.userName">{{user.userName}}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="操作时间" prop="createTime" style="margin-top: 10px">
            <el-date-picker clearable
                            v-model="saleOutQueryParams.createTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择操作时间">
            </el-date-picker>
          </el-form-item>
        </div>
        <el-form-item style="margin-top: 10px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" style="height: 35px">搜索</el-button>
        </el-form-item>
      </el-form>
      <div style="border: 1px gainsboro solid;border-radius: 3px;">
        <el-table height="400px" v-loading="loading" :data="this.SaleOutSheetList" @row-click="handleRowClick">
          <el-table-column width="30" align="center">
            <template slot-scope="scope">
              <el-radio :label="scope.$index" v-model="selectedRowIndex" @change.native="handleRadioChange(scope.$index)"><span style="display: none">0</span></el-radio>
            </template>
          </el-table-column>
          <el-table-column label="业务单据号" align="left" prop="code" width="230px"/>
          <el-table-column label="业务类型" align="left" prop="bizType" width="150">
            <template slot-scope="scope">
              <span>{{ '销售出库单'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" align="left" prop="scName" width="120px"/>
          <el-table-column label="收件人" align="left" prop="customerName" width="120px"/>
          <el-table-column label="操作时间" align="left" prop="createTime" width="200px">
            <template slot-scope="scope">
              <span>{{parseTime(scope.row.createTime, '{y}-{m}-{d}')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作人" align="left" prop="createBy" width="100px"/>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="saleOutFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import {listUser} from "@/api/system/user";
import { listTblLogisticsSheet, getTblLogisticsSheet, delTblLogisticsSheet, addTblLogisticsSheet, updateTblLogisticsSheet } from "@/api/system/TblLogisticsSheet";
import {getLogisticsCompany, listLogisticsCompany} from "@/api/system/LogisticsCompany";
import {listSheet} from "@/api/system/outsheet";
import {listCity} from "@/api/system/City";
import {onFreeze} from "core-js/internals/internal-metadata";

export default {
  name: "orderAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 物流明细表格数据
      tblLogisticsSheetDetailList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
      },

      // 表单参数
      form: {
        baseDataLogisticsCompany:{
          name:""
        }
      },

      // 表单校验
       rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },

      // 查询参数
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        shortName: null,
        skuCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        available: null,
        createTime: null,
      },
      //物流表数据
      LogisticsSheetList:[],

      LogisticsSaleOutList:[],

      //物流表ID数据
      LogisticsSheetAllList:[],
      //物流详情表ID数据
      LogisticsSheetDetailAllList:[],

      //出库单数据
      SaleOutSheetList:[],
      selectedRowIndex: -1, // 选中的行索引
      selectedRowData: null, // 选中的行数据

      //出库单弹窗
      saleOutFormVisible: false,
      saleOutQueryParams:{
        code:null,
        createBy:null,
        createTime:null,
        status:0
      },
      saleOutForm: {
      },
      formLabelWidth: '120px',

      //用户列表
      UserList: [],

      //地区
      options1:[],
      addressParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        logisticsNo: null,
        logisticsCompanyId: null,
        status: null,
        deliveryBy: null,
        deliveryTime: null,
        createById: null,
        createTime: null,
      },

      // 物流公司
      logisticsCompany: [],
    };
  },
  created() {
    //物理获取
    this.getList();
    //用户数据
    this.getUserList();
    //地址
    this.getCityList();
    //物流公司
    this.selectLogisticsCompany();

    //物流数据
    if (this.$route.query.id!=null){
      this.selectTblLogisticsSave();
    }
    this.loading = false;
  },
  methods: {
    parseTime,

    //物流数据
    getList() {
      this.loading = true;

      this.LogisticsSheetAllList = [];
      this.LogisticsSaleOutList = [];
      this.LogisticsSheetDetailAllList = [];

      listTblLogisticsSheet(this.queryParams).then(response => {
        this.LogisticsSheetList = response.rows;
        let tblLogisticsSheetList = response.rows;
        for (let i = 0; i < tblLogisticsSheetList.length; i++) {
          this.LogisticsSheetAllList.push(tblLogisticsSheetList[i].id)
          for (let j = 0; j < tblLogisticsSheetList[i].tblLogisticsSheetDetailList.length; j++) {
            this.LogisticsSheetDetailAllList.push(tblLogisticsSheetList[i].tblLogisticsSheetDetailList[j].id)
            this.LogisticsSaleOutList.push(tblLogisticsSheetList[i].tblLogisticsSheetDetailList[j].bizId)
          }
        }
      });
    },

    //查询物流公司
    selectLogisticsCompany(){
      listLogisticsCompany().then(response => {
        this.logisticsCompany = response.rows;
      });
    },
    /** 查询销售出库单列表 */
    getOutSheetList() {
      this.loading = true;
      listSheet(this.saleOutQueryParams).then(response => {
        this.SaleOutSheetList = [];
        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          if (!this.LogisticsSaleOutList.includes(list[i].id)){
            this.SaleOutSheetList.push(list[i]);
          }
        }

        this.loading = false;
      });
    },
    /** 查询物流详情 */
    selectTblLogisticsSave(){
      const id = this.$route.query.id
      getTblLogisticsSheet(id).then(response => {
        //物流
        this.form = response.data;
        //物流详情
        this.tblLogisticsSheetDetailList = response.data.tblLogisticsSheetDetailList;

        this.form.senderValue = [this.form.senderProvinceId, this.form.senderCityId, this.form.senderDistrictId]
        this.form.receiverValue = [this.form.receiverProvinceId, this.form.receiverCityId, this.form.receiverDistrictId]

        this.loading = false;
      });
    },

    //订单点击事件
    selectOrder() {
      this.saleOutFormVisible=true;
      this.getOutSheetList();
    },

    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.saleOutQueryParams.pageNum = 1;
      this.getOutSheetList();
    },

    handleRowClick(row, column, event) {
      this.selectedRowIndex = this.SaleOutSheetList.indexOf(row);
      this.selectedRowData = row; // 更新选中的行数据
    },
    handleRadioChange(index) {
      this.selectedRowIndex = index;
      // 清除其他行的选中状态
      this.$refs.singleTable.clearCurrentRow();
      this.$refs.singleTable.setCurrentRow(this.SaleOutSheetList[index]);
      this.selectedRowData = this.SaleOutSheetList[index]; // 更新选中的行数据
    },
    handleConfirm() {
      if (this.selectedRowData) {
        // 将选中的行数据传递给父组件
        this.$emit('order-selected', this.selectedRowData);
      }

      this.tblLogisticsSheetDetailList=[]
      let str=[{
        id:null,
        sheetId:null,
        bizId:this.selectedRowData.id,
        bizType:1,
        tblSaleOutSheet:this.selectedRowData,
      }]
      this.tblLogisticsSheetDetailList=str

      this.saleOutFormVisible = false; // 关闭弹窗
    },

    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm() {
      if(this.formInfo()){
        if (this.form.id != null) {
          updateTblLogisticsSheet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.LogisticsSheetAllList);
          var code = getOrderCode(this.LogisticsSheetList);
          this.form.id=newId;
          this.form.code=code;
          for (var i = 0; i < this.tblLogisticsSheetDetailList.length; i++) {
            let id=generateUniqueId(this.LogisticsSheetDetailAllList)
            this.tblLogisticsSheetDetailList[i].id = id;
            this.LogisticsSheetDetailAllList.push(id)
            this.tblLogisticsSheetDetailList[i].sheetId = newId;
          }
          this.form.tblLogisticsSheetDetailList=this.tblLogisticsSheetDetailList;
          this.form.senderProvinceId=this.form.senderValue[0];
          this.form.senderCityId=this.form.senderValue[1];
          this.form.senderDistrictId=this.form.senderValue[2];
          this.form.receiverProvinceId=this.form.receiverValue[0];
          this.form.receiverCityId=this.form.receiverValue[1];
          this.form.receiverDistrictId=this.form.receiverValue[2];
          this.form.createBy="系统管理员";
          this.form.createById="1";
          this.form.updateBy="系统管理员";
          this.form.updateById="1";
          this.form.status=0;

          addTblLogisticsSheet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      if (this.tblLogisticsSheetDetailList==null || this.tblLogisticsSheetDetailList.length<=0){
        this.$modal.msgError("请选择业务单据");
        return false;
      }
      if (this.form.senderName==null){
        this.$modal.msgError("请完善寄件人姓名");
        return false;
      }
      if (this.form.senderTelephone==null){
        this.$modal.msgError("请完善寄件人联系电话");
        return false;
      }
      if (this.form.senderValue==null){
        this.$modal.msgError("请选择寄件人地区");
        return false;
      }
      if (this.form.senderAddress==null){
        this.$modal.msgError("请完善寄件人详细地址");
        return false;
      }
      if (this.form.receiverName==null){
        this.$modal.msgError("请完善收件人姓名");
        return false;
      }
      if (this.form.receiverTelephone==null){
        this.$modal.msgError("请完善收件人联系电话");
        return false;
      }
      if (this.form.receiverValue==null){
        this.$modal.msgError("请选择收件人地区");
        return false;
      }
      if (this.form.receiverAddress==null){
        this.$modal.msgError("请完善收件人详细地址");
        return false;
      }
      if (this.form.logisticsCompanyId==null){
        this.$modal.msgError("请选择物理公司");
        return false;
      }
      if (this.form.totalWeight==null){
        this.$modal.msgError("请输入总重量");
        return false;
      }
      if (this.form.totalVolume==null){
        this.$modal.msgError("请输入总重体积");
        return false;
      }

      return true;
    },


    //地区框
    getCityList() {
      listCity(this.addressParams).then(response => {
        this.options1 = response.rows;
      });
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.refresh = true;
    next();
  },
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="WLGL";    //物流管理
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>

